﻿using System.IO;
using ResxHelper.Logic.Formatters;
using ResxHelper.Object;
using System;
using System.Windows.Input;

namespace ResxHelper.Logic.Actions
{
    public class SaveExcelAction : ICommand
    {
        private readonly ResourceFile _input;
        private readonly string _savePath;

        public SaveExcelAction(ResourceFile file, string savePath)
        {
            _input = file;
            _savePath = savePath;
        }

        public bool CanExecute(object parameter)
        {
            return
                _input != null &&
                !_input.Equals(new ResourceFile()) &&
                !string.IsNullOrEmpty(_savePath);
        }

        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            var excelGuts = ResourceFileFormatterFactory.GetFormatter(_input, SaveFileType.Excel).Run();
            using (var stream = new MemoryStream(Convert.FromBase64String(excelGuts)))
            {
                using (var fileStream = File.Create(_savePath, (int)stream.Length))
                {
                    var streamBytes = new byte[stream.Length];
                    stream.Read(streamBytes, 0, streamBytes.Length);
                    fileStream.Write(streamBytes, 0, streamBytes.Length);
                }
            }
        }
    }
}
